package com.copa.l617;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author copa
 * @createDate 2022-08-09 09:38
 * @function 深度优先遍历
 */
public class Test2 {

    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null) {
            // 如果两者都没有，直接返回null
            return null;
        }
        if (root1 == null) {
            // 如果root1没有，直接返回root2
            return root2;
        }
        if (root2 == null) {
            // 如果root2没有，直接返回root1
            return root1;
        }
        // 遍历到这里证明两数有东西，计算
        TreeNode result = new TreeNode(root1.val + root2.val);
        // 使劲遍历两树左子树
        result.left = mergeTrees(root1.left, root2.left);
        // 使劲遍历两树右子树
        result.right = mergeTrees(root1.right, root2.right);
        return result;
    }

    public static void main(String[] args) {
        TreeNode root1 = new TreeNode(1);
        root1.left = new TreeNode(3);
        root1.right = new TreeNode(2);
        root1.left.left = new TreeNode(5);
        TreeNode root2 = new TreeNode(2);
        root2.left = new TreeNode(1);
        root2.right = new TreeNode(3);
        root2.left.right = new TreeNode(4);
        root2.right.right = new TreeNode(7);
        TreeNode result = new Test2().mergeTrees(root1, root2);
        if (result == null) {
            System.out.println("没有树节点");
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(result);
        while (queue.size() > 0) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                System.out.print(node.val + "\t");
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                size--;
            }
        }
    }
}
